﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.Reflection;
using DevExpress.XtraEditors;
using CNCSoft.EWinform.ERPApps;
using Common;
using System.IO;
using DevExpress.XtraBars;
//using UpdateSoft;
using CNCSoft.ESecurity.Cryptography;
using System.Data.SqlClient;

using CNCSoft.EData;

namespace CNCSoft.ErpApps.TMS
{
    public partial class FormMain : Form //DevExpress.XtraEditors.XtraForm
    {
        #region [ Variables Declaration ]
        MenuPriviledgeSupporter mps;

        clsCommon mclsCommon;//class common

        public string strConnetionString = "";
        public string strUserID = "";
        public string strlanguage = "";
        public string mstrSqlServerName = "";
        public WorkingSessionInfo WSInfo = null;//dugn de goi report
        public string mstrErr = "";
        //string skinMask = "Skin: ";

        //khia bao public de load dong dung cho login, logout
        private bool mblnRestart = true;
        public Object mCallMenuShowDialog = null;
        public string mstrMenuID = "";
        //private bool mblnFormLoad = true;//status form load

        string _PropertiesFile;

        #endregion

        public FormMain()
        {
            InitializeComponent();
        }

        public FormMain(string PropertiesFile)
        {
            _PropertiesFile = Application.StartupPath + "\\" + PropertiesFile;

            InitializeComponent();
        }
       
        private void SetWindowsState()
        {
            try
            {
                CNCSoft.Common clsCom = new CNCSoft.Common();
                //clsCom.TestSaveConfig();
                string strWindowState = clsCom.GetConfigSetting("WindowState", "Maximized",
                       Application.StartupPath + "\\UserConfig.xml");
                //clsCom = null;
                if (strWindowState != "Maximized")
                {
                    if (Screen.PrimaryScreen.WorkingArea.Width <= 1024)
                        this.WindowState = FormWindowState.Maximized;
                    else
                    {
                        //Screen.PrimaryScreen.WorkingArea.Height
                        string strWindowWidth = clsCom.GetConfigSetting("WindowWidth", "980",
                               Application.StartupPath + "\\UserConfig.xml");
                        string strWindowHeight = clsCom.GetConfigSetting("WindowHeight", "690",
                               Application.StartupPath + "\\UserConfig.xml");
                        if(Screen.PrimaryScreen.WorkingArea.Width > int.Parse(strWindowWidth))
                            this.Width = int.Parse(strWindowWidth);
                        else
                            this.Width = Screen.PrimaryScreen.WorkingArea.Width;
                        if (Screen.PrimaryScreen.WorkingArea.Height > int.Parse(strWindowHeight))
                            this.Height = int.Parse(strWindowHeight);
                        else
                            this.Height = Screen.PrimaryScreen.WorkingArea.Height;
                    }
                    //20110211: start top = 0, left = center
                    this.Location = new Point((Screen.PrimaryScreen.WorkingArea.Width - this.Width) / 2, 0);
                }
                else
                {
                    this.WindowState = FormWindowState.Maximized;
                }
                clsCom = null;
                this.Show();
                this.ResumeLayout();
            }
            catch (Exception ex1) { }
        }

        protected override void Dispose(bool disposing)
        {

            if (disposing && (components != null))
            {
                components.Dispose();
            
                //save config
                string strWindowState = "";
                CNCSoft.Common clsCom = new CNCSoft.Common();
                //clsCom.TestSaveConfig();
                if (this.WindowState == FormWindowState.Maximized)
                    strWindowState = "Maximized";
                else
                {
                    try
                    {
                        strWindowState = "Normal";
                        clsCom.WriteConfigSetting("WindowWidth", this.Width.ToString(),
                               Application.StartupPath + "\\UserConfig.xml");
                        clsCom.WriteConfigSetting("WindowHeight", this.Height.ToString(),
                               Application.StartupPath + "\\UserConfig.xml");
                    }
                    catch (Exception exr) { }//ghi file loi
                }
                try
                    {
                        clsCom.WriteConfigSetting("WindowState", strWindowState,
                            Application.StartupPath + "\\UserConfig.xml");
                    }
                catch (Exception exr) { }//ghi file loi
                clsCom = null;

                //20110726: sanh them tracelogout
                try
                {
                    FormLoginTMS login = new FormLoginTMS(GlobalVariable.WSInfo);
                    login.ConnectionString = GlobalVariable.WSInfo.ConnectionString;
                    //login.TraceLogout(GlobalVariable.WSInfo.UserID);
                    login.Dispose();
                    login = null;

                    //MessageBox.Show("Call trace logout");
                }
                catch (Exception ext) { }
            }
            base.Dispose(disposing);
        }

        
        private void FormMain_Load(object sender, EventArgs e)
        {
            pictureBoxMainBackGround.Visible = false;

            mclsCommon = new clsCommon();

            try
            {
                mblnRestart = false;

                this.Activate();

                //LoadImageBackGround();

                //set default system format number and datetime for software
                mclsCommon.SystemFormatNumAndDate();

                FormMainLoad1();

                if (GlobalVariable.WSInfo.UserID.ToUpper() != "TEST")
                {
                    if (GlobalVariable.WSInfo.CompanyID.ToUpper() == "ENGLISH")
                    {
                        frmMainDashBoard frmDashBoard = new frmMainDashBoard();
                        frmDashBoard.MdiParent = this;
                        frmDashBoard.Show();
                    }
                }

                //FormHomeTest frmHome = new FormHomeTest();
                //frmHome.MdiParent = this;
                //frmHome.Show();


                InitSkins();

                SetWindowsState();
            }
            catch (Exception ex)
            {
                mclsCommon.ShowErrorMessage(MethodBase.GetCurrentMethod().Name, ex);
            }
            
        }

        //load background
        private void LoadImageBackGround()
        {
            try
            {
                pictureBoxMainBackGround.Image = null;
                string strBackGroundFileName = Application.StartupPath + "\\background_" + GlobalVariable.WSInfo.CompanyID + ".jpg";
                if (File.Exists(strBackGroundFileName))
                {
                    FileStream ins = File.OpenRead(strBackGroundFileName);
                    Image img = Image.FromStream(ins);
                    ins.Close();
                    pictureBoxMainBackGround.Image = img;
                    //pictureBoxMainBackGround.BackgroundImageLayout = ImageLayout.Stretch;
                    pictureBoxMainBackGround.Visible = true;
                }
            }
            catch (Exception ex)
            {
                mclsCommon.ShowErrorMessage(MethodBase.GetCurrentMethod().Name, ex);
            }
        }
        
        //private void btnCreateSal_Click(object sender, EventArgs e)
        //{
        //    Form frm = this;
        //    while (frm.ParentForm != null) frm = frm.ParentForm;
        //    mclsCommon.SetFieldValue(frm, "mstrMenuID", "mnuDanhSachNghiViec");
        //    //muon goi show dislog thi dung code duoi, ko thi la goi mac dinh theo menu
        //    //mclsCommon.SetFieldValue(frm, "mCallMenuShowDialog", true);
        //    mclsCommon.ExceuteMethod(frm, "MenuClick");
        //}
        public void MenuClick()
        {
            if (mstrMenuID == "Help" || mstrMenuID == "FixHelp")
            {
                string strQuickHelpURL = "";//
                if (mstrMenuID == "Help")
                    strQuickHelpURL = GlobalVariable.WSInfo.getAppProperty("SYS_QuickHelpURL", "");
                else
                    strQuickHelpURL = GlobalVariable.WSInfo.getAppProperty("SYS_CommonErrorFixURL", "");

                if (strQuickHelpURL != "")
                    System.Diagnostics.Process.Start(strQuickHelpURL);
            }
            else
            {
                if (mCallMenuShowDialog == null)
                    //MessageBox.Show("Click menu show dialog");
                    //mps.DevExMenuItemsClick(mstrMenuID);
                    mps.MenuItemsClick(mstrMenuID);
                else
                    //mps.DevExMenuItemsClick(mstrMenuID, (bool)mCallMenuShowDialog);
                    mps.MenuItemsClick(mstrMenuID, (bool)mCallMenuShowDialog);
            }
            mCallMenuShowDialog = null;

        }

        //khia bao public de load dong dung cho login, logout
        public void FormMainLoad()
        {
            
            CNCSoft.Common clsCom = new CNCSoft.Common();
            try
            {
                //clsCom.TestSaveConfig();
                clsCom.WriteConfigSetting("RunAutoLogin", "0",
                       Application.StartupPath + "\\UserConfig.xml");
            }
            catch (Exception exr) { }//loi ghi file

            clsCom = null;

            FormMainLoad1();
        }

        //khia bao public de load dong dung cho login, logout
        public void FormMainLoad1()
        {
            //Xac dinh cho dung file Connect
            GlobalVariable.WSInfo.AppPropertiesPath = _PropertiesFile;
            GlobalVariable.WSInfo.reinitAppProperty();

            FormLoginTMS login;
            
            CNCSoft.Common clsCom = new CNCSoft.Common();

            try
            {
                string sAccountLogin = GlobalVariable.WSInfo.UserID;

                //clsCom.TestSaveConfig();
                string strRunAutoLogin = clsCom.GetConfigSetting("RunAutoLogin", "1",
                       Application.StartupPath + "\\UserConfig.xml");
                //clsCom = null;

                //goi form login
                
                //login = new FormLoginTMS(GlobalVariable.WSInfo);
                //login.ConnectionString = GlobalVariable.WSInfo.ConnectionString;
                login = new FormLoginTMS(GlobalVariable.WSInfo.ConnectionString);
                //login.AllowAutoLogin = strRunAutoLogin == "1" ? true : false;
                //login.strOnlineDatabaseServer = GlobalVariable.strOnlineDatabaseServer;

                //neu nhan cancle thi thoat
                if (login.ShowDialog() != DialogResult.OK)
                {
                    login.Close();
                    login.Dispose();
                    this.Close();
                    this.Dispose();
                    Application.Exit();
                    return;
                }
                
               // mclsCommon.CloseWaitDialog();
                //mclsCommon.CreateWaitDialog();
                mclsCommon.SetWaitDialogCaption("Check loging...");

                if (mps != null)
                {
                    mps.Dispose();
                }

                GlobalVariable.WSInfo.UserID = login.UserID;
                GlobalVariable.WSInfo.UserName = login.UserName;
                GlobalVariable.WSInfo.WorkingDate = login.WorkingDate;
                GlobalVariable.WSInfo.Language = login.Language ;
                GlobalVariable.WSInfo.CompanyID = login.CompanyID;

                strConnetionString = GlobalVariable.WSInfo.ConnectionString; //dung de goi dong menu login
                strUserID = GlobalVariable.WSInfo.UserID;//dung de goi dong menu login
                strlanguage = GlobalVariable.WSInfo.Language;
                mstrSqlServerName = GlobalVariable.WSInfo.SqlServerName;//dung trong dang ky ban quyen pm
                WSInfo = GlobalVariable.WSInfo;//dugn de goi menu dong goi report

                mps = new MenuPriviledgeSupporter(this, GlobalVariable.WSInfo.ConnectionString);
                mps.LoadMenuPriviledge(login.UserID);
                
                mps.FromMainMDI = this;

                string strMenuGruop = SQLHelper.ExecuteScalar(GlobalVariable.WSInfo.ConnectionString ,"SELECT MenuGroup FROM DM_DONVI WHERE MaDonVi = '" + GlobalVariable.WSInfo.CompanyID + "'").ToString();
                this.Menu = mps.LoadMenu(strMenuGruop, true, login.Language);

                //mps.SynchronizeToolbarToMenu(this.toolBar1);

                if (login.Authenticated)
                {
                    GlobalVariable.WSInfo.WorkingDate = login.WorkingDate;
                    GlobalVariable.WSInfo.UserID = login.UserID;
                    barCompany.Caption = GlobalVariable.WSInfo.CompanyName ;
                    barUser.Caption = GlobalVariable.WSInfo.UserID;
                    barDate.Caption = GlobalVariable.WSInfo.WorkingDate.ToString("dd/MM/yyyy");
                    barStaticDatabase.Caption = GlobalVariable.WSInfo.SqlServerName;
                    barStaticItem_Language.Caption = GlobalVariable.WSInfo.Language;

                    //Kiem tra version de AutoUpdate (from website)
                    string strVersion = CheckVersionFromInternet("");
                    if (strVersion != "" && Application.ProductVersion.ToString() != strVersion)
                    {
                        CNCSoft.ErpApps.TMS.frmAutoUpdate frmUpdate = new CNCSoft.ErpApps.TMS.frmAutoUpdate();
                        frmUpdate.ShowDialog();
                        frmUpdate.Dispose(); ;  //Update
                    }
                    
                    //Title main
                    this.Text = GlobalVariable.WSInfo.getAppProperty("ApplicationTitle", "");
                    
                    string forDonVi = " for " + GlobalVariable.WSInfo.CompanyID;
                    if (this.Text.IndexOf(forDonVi) < 0)
                        this.Text = this.Text + forDonVi;
                    
                    if (this.Text.IndexOf("Version") < 0)
                        this.Text = this.Text + "  (Version: " + Application.ProductVersion.ToString() + ")";
                    
                    //Background Image
                    LoadImageBackGround();

                }
                else
                {
                    //this.toolBar1.Buttons[0].Enabled = true;
                    //this.toolBar1.Buttons[this.toolBar1.Buttons.Count - 1].Enabled = true;
                }

                string skinName =  clsCom.GetConfigSetting("SkinName", "",
                       Application.StartupPath + "\\UserConfig.xml");
                if (skinName != "")
                {
                    barStatusItem1Skin.Caption = "Skin: " + skinName;
                    DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = skinName;
                    DevExpress.LookAndFeel.LookAndFeelHelper.ForceDefaultLookAndFeelChanged();
                }

                if (GlobalVariable.strOnlineDatabaseServer == GlobalVariable.WSInfo.SqlServerName)
                    GlobalVariable.blnDemo = false;
                else
                
                //check license
                //{
                //    if(GlobalVariable.blnCodingRun == false)
                //        mclsCommon.CheckLicense();
                //}

                try
                {
                    clsCom.WriteConfigSetting("RunAutoLogin", "1",
                       Application.StartupPath + "\\UserConfig.xml");
                }
                catch (Exception exr) { }

                clsCom = null;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Co loi xay ra khi load form main FormMainLoad: " + ex.Message,"Thong bao loi",MessageBoxButtons.OK,MessageBoxIcon.Error);
            }


            //mclsCommon.CloseWaitDialog();
        }


        private string CheckVersionFromInternet(string URL)
        {
            string uriString = @"http://cncaptech.edu.vn/TMS/VietAnh/TMSCurrentVersion.txt";
            try
            {
                System.Net.WebClient myWebClient = new System.Net.WebClient();
                System.IO.Stream myStream = myWebClient.OpenRead(uriString);
                System.IO.StreamReader sr = new System.IO.StreamReader(myStream);
                return sr.ReadToEnd();
            }
            catch
            {
                return "";
            }
        }


        //20110716: sanh them tu dong check auto update 1 ngay 1 lan
        private void CheckUpdateSoft(CNCSoft.Common clsCom, bool blnAutoUpdate)
        {
            /*
            bool blnCallUpdateCheck = true;

            try
            {
                string strLastUpdateCheck = clsCom.GetConfigSetting("LastUpdateCheck", "",
                    Application.StartupPath + "\\UserConfig.xml");

                string strAutoCheckUpdate = clsCom.GetConfigSetting("AutoCheckUpdate", "1",
                    Application.StartupPath + "\\UserConfig.xml");

                //neu bo wa ko check update thi thoat
                if (strAutoCheckUpdate == "0")
                    return;

                //neu = nhau tuc ngay hom nay da check roi
                if (strLastUpdateCheck.Trim() == DateTime.Now.ToString("yyyy/MM/dd"))
                    blnCallUpdateCheck = false;

                //neu goi check update
                if (blnCallUpdateCheck || blnAutoUpdate)
                {
                    bool blnCallUpdate = false;

                    UpdateCommon clsUpCom = new UpdateCommon();
                    clsUpCom.strConnString = GlobalVariable.WSInfo.ConnectionString;

                    clsUpCom.strProjectCode = GlobalVariable.WSInfo.getAppProperty("ProjectCode", "SVHRIS");
                    //neu trong ko co se tu lay user config sau, user config van ko co thi lay mac dinh
                    clsUpCom.strProjectType = GlobalVariable.WSInfo.getAppProperty("ProjectType", "");

                    string strUpdateContent = "";

                    blnCallUpdate = clsUpCom.CheckUpdate(ref strUpdateContent);
                    clsUpCom = null;

                    try
                    {
                        clsCom.WriteConfigSetting("LastUpdateCheck", DateTime.Now.ToString("yyyy/MM/dd"),
                              Application.StartupPath + "\\UserConfig.xml");
                    }
                    catch (Exception exr) { }

                    //goi update soft
                    if (blnCallUpdate)
                    {
                        string strMess = "Có thông tin cập nhật phần mềm mới, bạn có muốn cập nhật phần mềm không?";
                        //strUpdateContent
                        strMess += "\r\nNội dung cập nhật: \r\n\r\n" + strUpdateContent;

                        if (MessageBox.Show(strMess, "Thong bao", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.No)
                        {
                            //neu chon ko thi tiep tuc hoi lan sau co tu kiem tra hay ko
                            strMess = "Bạn có muốn phần mềm tự động kiểm tra thông tin cập nhật phần mềm mới nữa không?" +
                                "\r\nNếu chọn không bạn có thể tự kiểm tra ở chức năng Hệ thống -> Cập nhật phần mềm?";
                            if (MessageBox.Show(strMess, "Thong bao", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.No)
                            {
                                clsCom.WriteConfigSetting("AutoCheckUpdate", "0",
                                    Application.StartupPath + "\\UserConfig.xml");
                            }
                            //thoat 
                            return;
                        }

                        //neu nhan update nua thi goi nguoc update
                        //System.Diagnostics.Process.Start(Application.StartupPath + "\\UpdateTools.exe");
                        System.Diagnostics.ProcessStartInfo proc = new System.Diagnostics.ProcessStartInfo();

                        proc.UseShellExecute = true;
                        proc.WorkingDirectory = Environment.CurrentDirectory;
                        proc.FileName = Application.StartupPath + "\\UpdateTools.exe";
                        proc.Verb = "runas";

                        try
                        {
                            System.Diagnostics.Process.Start(proc);
                        }
                        catch
                        {
                            // The user refused the elevation.
                            // Do nothing and return directly ...
                            return;
                        }

                        Application.Exit();
                        this.Close();
                    }
                }//if (blnCallUpdateCheck)

            }
            catch (Exception ex)
            {
                //bo wa loi check update
                MessageBox.Show("Co loi xay ra khi load form main CheckUpdateSoft: " + ex.Message, "Thong bao loi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
           */
        }

        //20110716: sanh them tu dong check auto update 1 ngay 1 lan
        private bool CheckRun(CNCSoft.Common clsCom)
        {
            try{

                //1 ngay check run hop le 1 lan, khi check xong ghi config nhu sau
                //  ky tu 1 la so dau cua ngay do: ngay 7 => 0, ngay 17 => 1
                //  ky tu 2 la so bieu hien su hop le = 9 - ky tu 1, vi du ky tu 1 la 0 => 9, 1 => 8 (ki tu 1 chi tu 1 -> 3)
                
                //  ky tu cuoi -1  la so thu 2 (so sau) cua ngay do: ngay 7 => 7, ngay 17 => 7
                //  ky tu cuoi la so bieu hien su hop le = 9 - ky tu cuoi - 1, vi du ky tu cuoi la 7 => 2, 9 => 0, 0 => 9

                //cac ki tu giua cua config nay ghi khi lan dau chay = cpu+hdd
                ////ghi config lan dau dung cho check run
                //clsCom.WriteConfigSetting("SYS_Info1", strQuickHelpURL, Application.StartupPath + "\\UserConfig.xml");
                //neu van chua co thong tin tuc la da chay dang ky truoc
                bool blnTraceLogin = false;

                string strSYS_Info1 = clsCom.GetConfigSetting("SYS_Info1", "",
                       Application.StartupPath + "\\UserConfig.xml");
                //neu ban dau chua co thong tin thi lay computerInfo da luu ben register
                if (strSYS_Info1.Trim() == "")
                {
                    strSYS_Info1 = clsCom.GetConfigSetting("SYS_InfoC", "",
                       Application.StartupPath + "\\UserConfig.xml");

                    ////tam code the
                    //blnTraceLogin = true;
                }

                ////  thi goi lai de lay thong tin
                //if (strSYS_Info1.Trim() == "")
                //{
                //    FormRegister frmReg = new FormRegister();
                //    frmReg.WriteComputerInfo();

                //    frmReg.Dispose();
                //    frmReg = null;

                //    //sau khi ghi xong thi load lai
                //    strSYS_Info1 = clsCom.GetConfigSetting("SYS_InfoC", "",
                //       Application.StartupPath + "\\UserConfig.xml");

                //    blnTraceLogin = true;
                //}

                string strCurDate = "";
                strSYS_Info1 = strSYS_Info1.Trim();

                //  ky tu 1 la so dau cua ngay do: ngay 7 => 0, ngay 17 => 1
                if (strSYS_Info1.Length >= 1) strCurDate += strSYS_Info1.Substring(0, 1);
                //  ky tu cuoi -1  la so thu 2 (so sau) cua ngay do: ngay 7 => 7, ngay 17 => 7
                if (strSYS_Info1.Length >= 4) strCurDate += strSYS_Info1.Substring(strSYS_Info1.Length-2, 1);

                bool blnOKLeft = false;
                bool blnOKRight = false;

                string strCheckOK = "";
                //  ky tu 2 la so bieu hien su hop le = 9 - ky tu 1, vi du ky tu 1 la 0 => 9, 1 => 8 (ki tu 1 chi tu 1 -> 3)
                if (strSYS_Info1.Length >= 2) strCheckOK += strSYS_Info1.Substring(1, 1);
                //  ky tu cuoi la so bieu hien su hop le = 9 - ky tu cuoi - 1, vi du ky tu cuoi la 7 => 2, 9 => 0, 0 => 9
                if (strSYS_Info1.Length >= 4) strCheckOK += strSYS_Info1.Substring(strSYS_Info1.Length - 1, 1);
                try
                {
                    //  ky tu 2 la so bieu hien su hop le = 9 - ky tu 1, vi du ky tu 1 la 0 => 9, 1 => 8 (ki tu 1 chi tu 1 -> 3)
                    if (int.Parse(strCheckOK.Substring(0, 1)) == 9 - int.Parse(strCurDate.Substring(0, 1)))
                        blnOKLeft = true;
                    //  ky tu cuoi la so bieu hien su hop le = 9 - ky tu cuoi - 1, vi du ky tu cuoi la 7 => 2, 9 => 0, 0 => 9
                    if (int.Parse(strCheckOK.Substring(1, 1)) == 9 - int.Parse(strCurDate.Substring(1, 1)))
                        blnOKRight = true;

                }
                catch (Exception ex1) { }

                //neu ngay = ngay va okleft okright thi return
                if (strCurDate == DateTime.Now.ToString("dd") && blnOKLeft && blnOKRight)
                    return true;

                //ko return thi check
                //  mo ket noi online: neu loi mo ket noi online coi nhu bi fa bao cai lai
                //      check trong TraceLogin neu field isnull(ComputerLocked,0) where LogInfo = config.UserInfo2
                //          if ComputerLocked != nulll (fai co) va = 0 la ok else => bao la exit

                #region "---------- mo ket noi online de check: return _cnnStringOnline----------"
                //  mo ket noi online: neu loi mo ket noi online coi nhu bi fa bao cai lai
                DataProtector dp = new DataProtector();
                StringReader sr = new StringReader(dp.decrypt(AppPropertiesPath));
                DataSet ds = new DataSet();
                ds.ReadXml(sr);

                if (hashAP == null)
                    hashAP = new Hashtable();
                string strT = "";

                for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
                {
                    strT = Convert.ToString(ds.Tables[0].Rows[index][0]);
                    strT = strT.ToLower().Trim();
                    if (!hashAP.ContainsKey(strT))
                    {
                        hashAP.Add(strT, ds.Tables[0].Rows[index][1]);
                    }
                    //					if (!hashAP.ContainsKey(ds.Tables[0].Rows[index][0])) {
                    //						hashAP.Add(ds.Tables[0].Rows[index][0], ds.Tables[0].Rows[index][1]);
                    //					}

                }
                ds.Clear();
                ds.Dispose();
                ds = null;

                if (_cnnStringOnline == null || _cnnStringOnline == string.Empty)
                {
                    _cnnStringOnline = (string)hashAP["connectionstring"];
                    if (_cnnStringOnline == null || _cnnStringOnline == string.Empty)
                    {
                        MessageBox.Show("Phan mem khong tim thay file he thong hay file he thong da bi xoa, yeu cau cai lai hoac lien he nha cung cap de duoc ho tro", "Thong bao loi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        //this.Close();
                        //Application.Exit();
                        return false;
                    }
                    //else
                    //{
                    //    MessageBox.Show(_cnnStringOnline);
                    //}
                }
                #endregion "---------- end mo ket noi online de check----------"

                SqlConnection connOnline = new SqlConnection(_cnnStringOnline);
                connOnline.Open();

                string strComputerUser = clsCom.GetConfigSetting("SYS_InfoU", "",
                   Application.StartupPath + "\\UserConfig.xml");

                string strComputerInfo = clsCom.GetConfigSetting("SYS_InfoC", "",
                   Application.StartupPath + "\\UserConfig.xml");

                string strSQL = "select top 1 isnull(ComputerLocked,0) as ComputerLocked from [SYS_tblTraceLogin]  " +
                    "\r\n where 1 = 1 " +
                    "\r\n	and ComputerInfo = N'" + strComputerInfo + "'  " +
                    "\r\n order by isnull(ComputerLocked,0) desc ";// +
                    //"\r\n	and isnull(ComputerLocked,0) = 1";

                SqlCommand cmOnline = new SqlCommand(strSQL, connOnline);
                SqlDataReader dr = cmOnline.ExecuteReader();

                bool blnLocked = true;
                if (dr.Read())
                {
                    blnLocked = (bool)dr["ComputerLocked"];
                }
                else if (blnTraceLogin)
                {
                    //coi nhu trace login lan dau
                    //20110726: sanh them tracelogout
                    try
                    {
                        FormLogin login = new FormLogin(GlobalVariable.WSInfo);
                        login.ConnectionString = _cnnStringOnline;
                        login.TraceLogin();
                        login.Dispose();
                        login = null;

                        //tam cho = false
                        blnLocked = false;
                    }
                    catch (Exception ext) { }
                }
                
                dr.Close();
                dr = null;
                cmOnline.Dispose();
                cmOnline = null;

                connOnline.Close();
                connOnline.Dispose();
                connOnline = null;

                if (blnLocked)
                {
                    string strMess = "Không thể chạy phần mềm, có thể bạn đã bị khóa phần mềm vì thông tin người sử dụng đăng ký không hợp lệ!";
                    strMess += "\r\nHoặc thông tin cấu hình mặc định bị thay đổi, hãy thử cài lại phần mềm.";

                    strMess += "\r\n\r\nNếu bạn là khách hàng có nhu cầu sử dụng phần mềm thì hãy liên hệ chúng tôi để được hỗ trợ!";

                    MessageBox.Show(strMess, "Thong bao loi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    //this.Close();
                    //Application.Exit();

                    return false;
                }

                if (strSYS_Info1.Length > 4)
                    strSYS_Info1 = strSYS_Info1.Substring(2, strSYS_Info1.Length - 4);
                
                //  ky tu 2 la so bieu hien su hop le = 9 - ky tu 1, vi du ky tu 1 la 0 => 9, 1 => 8 (ki tu 1 chi tu 1 -> 3)
                strSYS_Info1 = (9 - int.Parse(DateTime.Now.ToString("dd").Substring(0, 1))).ToString() + strSYS_Info1;
                //  ky tu 1 la so dau cua ngay do: ngay 7 => 0, ngay 17 => 1

                strSYS_Info1 = DateTime.Now.ToString("dd").Substring(0, 1) + strSYS_Info1;
                //  ky tu cuoi -1  la so thu 2 (so sau) cua ngay do: ngay 7 => 7, ngay 17 => 7
                strSYS_Info1 = strSYS_Info1 + DateTime.Now.ToString("dd").Substring(1,1);
                //  ky tu cuoi la so bieu hien su hop le = 9 - ky tu cuoi - 1, vi du ky tu cuoi la 7 => 2, 9 => 0, 0 => 9
                strSYS_Info1 = strSYS_Info1 + (9 - int.Parse(DateTime.Now.ToString("dd").Substring(1, 1))).ToString();

                //ghi config
                try
                {
                    clsCom.WriteConfigSetting("SYS_Info1", strSYS_Info1,
                           Application.StartupPath + "\\UserConfig.xml");
                }
                catch (Exception ex)
                {
                }

                return true;
            }
            catch (Exception ex)
            {
                //neu loi ko co net ko connect dc online thi bo wa
                if (ex.Message.IndexOf("A network-related or instance-specific error occurred while establishing a connection to SQL Server") != -1)
                    return true;
                else
                {
                    MessageBox.Show("Co loi xay ra khi chay phan mem, hay install lai phan mem: " + ex.Message, "Thong bao loi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return false;
                }
            }
        }

        private string _cnnStringOnline = "";
        protected Hashtable hashAP = null; // application properties
        public string _app_properties_path_online = null;
        /// <summary>
        /// The path that store application configuration file (Ex: application.properties, application.properties.dkey,...);
        /// </summary>
        public string AppPropertiesPath
        {
            set { _app_properties_path_online = value; }
            get
            {
                if (_app_properties_path_online == null || _app_properties_path_online == string.Empty)
                {
                    _app_properties_path_online = System.Configuration.ConfigurationSettings.AppSettings["AppPropertiesPathOnline"];
                    if (_app_properties_path_online == null || _app_properties_path_online == string.Empty)
                    {
                        _app_properties_path_online = Application.StartupPath + @"\application.properties_SVHRISOnline";
                    }
                    return _app_properties_path_online;
                }
                else
                {
                    return _app_properties_path_online;
                }
            }
        }

        #region "code ko con dung nua"

        /*
        private void cmdSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //mclsCommon.Save((XtraForm)this.ActiveMdiChild);
            mclsCommon.ExceuteMethod(this.ActiveMdiChild, "Save");
        }

        private void cmdAddNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mclsCommon.AddNew((XtraForm)this.ActiveMdiChild);
        }

        private void cmdSaveNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mclsCommon.SaveNew((XtraForm)this.ActiveMdiChild);
        }

        private void cmdEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mclsCommon.Edit((XtraForm)this.ActiveMdiChild);
        }

        private void cmdCancle_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //mclsCommon.Cancle((XtraForm)this.ActiveMdiChild);
            mclsCommon.ExceuteMethod(this.ActiveMdiChild, "Cancle");
        }

        private void cmdDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mclsCommon.ExceuteMethod(this.ActiveMdiChild,"Delete");
        }

        private void cmdView_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mclsCommon.ExceuteMethod(this.ActiveMdiChild, "View");
        }

        private void cmdPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mclsCommon.ExceuteMethod(this.ActiveMdiChild, "Print");
        }

        private void cmdExport_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //mclsCommon.ExceuteMethod(this.ActiveMdiChild, "Export");
            
            Control ctlControl = this.ActiveMdiChild.ActiveControl;
            while (ctlControl is XtraForm)
            {
                ctlControl = ((XtraForm)ctlControl).ActiveControl;
            }
            mclsCommon.Export(ctlControl);
        }

        private void cmdFill_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            mclsCommon.ExceuteMethod(this.ActiveMdiChild, "Fill");
        
        }

        private void cmdHelp_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            FormMau frmFormMau = new FormMau();
            frmFormMau.MdiParent = this;
            frmFormMau.Show();
        }
        */
        #endregion "Code ko con dung nua

        void InitSkins()
        {
            barManager1.ForceInitialize();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.UserSkins.BonusSkins.Register();
            //DevExpress.Skins.SkinManager.EnableFormSkins();
            DevExpress.LookAndFeel.UserLookAndFeel.Default.UseWindowsXPTheme = false;
            DevExpress.LookAndFeel.UserLookAndFeel.Default.UseDefaultLookAndFeel = true;
            DevExpress.LookAndFeel.UserLookAndFeel.Default.Style = DevExpress.LookAndFeel.LookAndFeelStyle.Skin;
            
            DevExpress.XtraBars.Helpers.SkinHelper.InitSkinPopupMenu(barStatusItem1Skin);
            DevExpress.LookAndFeel.UserLookAndFeel.Default.StyleChanged += new EventHandler(Default_StyleChanged);

        }

        void Default_StyleChanged(object sender, EventArgs e)
        {
            var skin = DevExpress.Skins.CommonSkins.GetSkin(DevExpress.LookAndFeel.UserLookAndFeel.Default);
            barStatusItem1Skin.Caption = "Skin: " + skin.Name;

            CNCSoft.Common clsCom = new CNCSoft.Common();
            //clsCom.TestSaveConfig();
            try
            {
                clsCom.WriteConfigSetting("SkinName", skin.Name,
                        Application.StartupPath + "\\UserConfig.xml");
            }
            catch (Exception exr) { }
            clsCom = null;

        }

        private void MdiManager_PageAdded(object sender, DevExpress.XtraTabbedMdi.MdiTabPageEventArgs e)
        {
            pictureBoxMainBackGround.SendToBack();

            Icon icon = e.Page.MdiChild.Icon;
            if (icon == null) return;
            //neu la icon mac dinh thi return
            
            MemoryStream imageStream = new MemoryStream();
            icon.Save(imageStream);
            if (imageStream.ToArray().Length == 10134) return;

            Icon iconNew = (Icon.Size.Height !=16)?new Icon(icon, new Size(16, 16)):icon;

            e.Page.Image = iconNew.ToBitmap();


        }

        private void barDatabase_ItemClick(object sender, ItemClickEventArgs e)
        {
            DatabaseTool.DataConfig frmDataConfig = new DatabaseTool.DataConfig();
            frmDataConfig.mblnExitAppWhenCompleted = false;
            
            frmDataConfig.Activate();
            
            if (frmDataConfig.ShowDialog()== DialogResult.OK && GlobalVariable.WSInfo != null)
            {
                //20110726: sanh them tracelogout
                try
                {

                    FormLogin login = new FormLogin(GlobalVariable.WSInfo);
                    login.ConnectionString = GlobalVariable.WSInfo.ConnectionString;
                    login.TraceLogout(GlobalVariable.WSInfo.UserID);
                    login.Dispose();
                    login = null;

                    //MessageBox.Show("Call trace logout");
                }
                catch (Exception ext) { }

                GlobalVariable.WSInfo.reinitAppProperty();

                FormMainLoad1();
            }

            frmDataConfig.Dispose();
            frmDataConfig = null;
        }

        private void barStaticItem1_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void FormMain_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        
        private void FormMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.Tag == "Exit")
            {
                e.Cancel = false;
                return;
            }

            try
            {
                if (GlobalVariable.WSInfo.UserID == "" || GlobalVariable.WSInfo.UserID == null)
                    e.Cancel = false;  //Thoat khi khong login thanh cong
                else
                {
                        frmLogout  frmLgOut = new frmLogout();
                        frmLgOut.ShowDialog();
                        frmLgOut.Dispose();
                        e.Cancel = (frmLgOut.DialogResult == System.Windows.Forms.DialogResult.Cancel);
                }
            }
            catch (Exception ex)
            {
                e.Cancel = false;  //Thoat neu co loi (loi la do ghi thong tin logout)
            }
        }

        private void MdiManager_PageRemoved(object sender, DevExpress.XtraTabbedMdi.MdiTabPageEventArgs e)
        {
            if (MdiManager.Pages.Count == 0)
            {
                pictureBoxMainBackGround.BringToFront();
            }
        }

        

       //end  FormMainLoad

        //private void cmdPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        //{
        //    FormMau frmFormMau = new FormMau();
        //    frmFormMau.MdiParent = this;
        //    frmFormMau.Show();
        //}

    }
}